const { DataTypes } = require('sequelize');
const { nanoid } = require('nanoid');
const sequelize = require('../config/database');
const Inventory = require('./Inventory');

const InventoryTransaction = sequelize.define('InventoryTransaction', {
  id: {
    type: DataTypes.STRING,
    primaryKey: true,
    defaultValue: () => nanoid()
  },
  inventoryId: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '库存ID',
    references: {
      model: Inventory,
      key: 'id'
    }
  },
  type: {
    type: DataTypes.ENUM('入库', '出库', '初始化'),
    allowNull: false,
    comment: '操作类型'
  },
  quantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '操作数量'
  },
  beforeQuantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '操作前数量'
  },
  afterQuantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '操作后数量'
  },
  remark: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '备注'
  }
}, {
  timestamps: true,
  paranoid: true,
  tableName: 'inventory_transaction'
});

// 建立与Inventory的关联关系
InventoryTransaction.belongsTo(Inventory, {
  foreignKey: 'inventoryId',
  as: 'inventory'
});

Inventory.hasMany(InventoryTransaction, {
  foreignKey: 'inventoryId',
  as: 'transactions'
});

module.exports = InventoryTransaction;